package shiro.redis;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class RedisSessionDAO extends AbstractSessionDAO {
 
    private static Logger logger = LoggerFactory.getLogger(RedisSessionDAO.class);
    
    private String keyPrefix = "shiro_session:";
     
    @Override
    public void update(Session session) 
    {
        this.saveSession(session);
    }
     
    private void saveSession(Session session)
    {
        if(session == null || session.getId() == null)
        {
            logger.error("session or session id is null");
            return;
        }

        session.setTimeout(RedisManager.getExpireSeconds()*1000);

        RedisManager.put(session.getId(), session, RedisManager.getExpireSeconds());
    }
 
    @Override
    public void delete(Session session) 
    {
        if(session == null || session.getId() == null)
        {
            logger.error("session or session id is null");
            return;
        }
        RedisManager.del(session.getId());
    }
 
    @Override
    public Collection<Session> getActiveSessions() 
    {
        Set<Session> sessions = new HashSet<Session>();
         
        /*Set<byte[]> keys = RedisManager.keys(this.keyPrefix + "*");
        if(keys != null && keys.size() > 0)
        {
            for(byte[] key:keys)
            {
                Session s = (Session)SerializeUtils.valueFromBytes((byte[])RedisManager.get(key));
                sessions.add(s);
            }
        }*/
        return sessions;
    }
 
    @Override
    protected Serializable doCreate(Session session) 
    {
        Serializable sessionId = this.generateSessionId(session);  
        this.assignSessionId(session, sessionId);
        this.saveSession(session);
        return sessionId;
    }
 
    @Override
    protected Session doReadSession(Serializable sessionId) 
    {
        if(sessionId == null)
        {
        	logger.error("session id is null");
            return null;
        }
        Session s = RedisManager.get(sessionId);
        return s;
    }
 
    public String getKeyPrefix() 
    {
        return keyPrefix;
    }
 
    public void setKeyPrefix(String keyPrefix) 
    {
        this.keyPrefix = keyPrefix;
    }
     
}